import {
  addUserChannelAPI,
  delUserChannelByIdAPI,
  getAllChannelsAPI,
  getUserChannelsAPI,
} from '@/api/channel';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '..';
import { ActionType, ChannelType } from '../reducer/channel';

export const getAllChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/saveAllList', payload: res.data.channels });
  };
};

export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelsAPI();
      dispatch({ type: 'channel/saveUserList', payload: res.data.channels });
      return;
    }
    const localUserList = getLocalChannels();
    if (localUserList.length) {
      dispatch({ type: 'channel/saveUserList', payload: localUserList });
      return;
    }
    const result = await getAllChannelsAPI();
    const localList = result.data.channels.slice(0, 10);
    dispatch({ type: 'channel/saveUserList', payload: localList });
    setLocalChannels(localList);
  };
};

export const delUserChannelByIdAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    await delUserChannelByIdAPI(id);
    dispatch({ type: 'channel/delById', payload: id });
  };
};

export const addUserChannelAction = (newChannel: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    await addUserChannelAPI([newChannel]);
    dispatch({ type: 'channel/add', payload: newChannel });
  };
};

export const setCurrentIdAction = (id: number): ActionType => ({
  type: 'channel/setCurrentId',
  payload: id,
});
